const path = require('path')
const fs = require('fs')

class PublicController {

  upfile(req, res) {
    /* let { originalname, destination, filename } = req.file
    // 得到扩展名 .jpg
    let ext = path.extname(originalname)
    let filepath = path.resolve(path.join(destination, filename))
    fs.renameSync(filepath, filepath + ext)
    res.send({ url: '/uploads/' + filename + ext }) */

    let { filename, destination } = req.file

    // console.log(req.body, destination, filename)
    let oldpath = path.resolve(destination, filename)
    let newpath = path.resolve(destination, req.body.index)
    fs.renameSync(oldpath, newpath)
    res.send({ url: '/uploads/' + req.body.index })
  }

  merge(req, res) {
    let { count, name } = req.query
    let dirpath = path.resolve('./public/uploads')
    // 生成的目标文件
    let targetFile = path.join(dirpath, name)
    // 得到一个写入流
    let ws = fs.createWriteStream(targetFile)
    let index = 0
    streamToTarget()

    function streamToTarget() {
      if (index >= count) {
        // 写入完成
        return ws.end(() => console.log('写完毕了'))
      }
      let filepath = path.join(dirpath, '' + index)
      let rs = fs.createReadStream(filepath)
      rs.pipe(ws, { end: false })
      rs.on('end', () => {
        index++
        streamToTarget()
      })
    }
    res.send({ url: name })
  }

}

module.exports = new PublicController()
